<template>
  <el-image
    :src="realSrc"
    fit="cover"
    :style="`width:${realWidth};height:${realHeight};`"
    :preview-src-list="realSrcList"
    @click.stop="handlePreview"
  >
    <template #error>
      <div class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </template>
  </el-image>
  <el-dialog v-model="dialogVisible" append-to-body>
    <img :src="realSrc" style="display: block; max-width: 100%; margin: 0 auto" alt="#" />
  </el-dialog>
</template>

<script>
  import { createBaseConfig } from '@/config/core/base-config.js'
  const prefix = createBaseConfig().prefix
  export default {
    name: 'ImagePreview',
    props: {
      src: {
        type: String,
        default: ''
      },
      width: {
        type: [Number, String],
        default: '40px'
      },
      height: {
        type: [Number, String],
        default: '40px'
      },
      previewType: {
        type: [String, Number],
        default: ''
      },
      hasPrefix: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        dialogVisible: false
      }
    },
    methods: {
      handlePreview() {
        if (this.previewType === 1) {
          this.dialogVisible = true
        }
      }
    },
    computed: {
      realSrc() {
        if (!this.src) {
          return
        }
        if (!this.hasPrefix) {
          return 'https://' + this.src
        }
        if (this.src.startsWith(prefix)) {
          return this.src
        } else {
          return prefix + this.src
        }
      },
      realSrcList() {
        if (this.previewType === 1) {
          return []
        }
        if (!this.src) {
          return
        }
        let real_src_list = this.src.split(',')
        let srcList = []
        real_src_list.forEach((item) => {
          if (!this.hasPrefix) {
            return srcList.push('https://' + item)
          }
          if (this.src.startsWith(prefix)) {
            return srcList.push(item)
          } else {
            return srcList.push(prefix + item)
          }
        })
        return srcList
      },
      realWidth() {
        return typeof this.width == 'string' ? this.width : `${this.width}px`
      },
      realHeight() {
        return typeof this.height == 'string' ? this.height : `${this.height}px`
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-image {
    border-radius: 5px;
    background-color: #ebeef5;
    box-shadow: 0 0 5px 1px #ccc;
    :deep(.el-image__inner) {
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        transform: scale(1.2);
      }
    }
    :deep(.image-slot) {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      color: #909399;
      font-size: 30px;
    }
  }
</style>
